import { useState, useEffect } from "react";
import { invokeAsyncAPi, registerInformApi } from "@/xz-fn.js";
import {
  AUTH_TOKEN,
  AUTH_USER,
  AUTH_LOGIN,
  AUTH_ONLINE_TOKEN,
} from "@/utils/constants";
import System from "@/models/system";
function useUserInfo() {
  const [userInfo, setUserInfo] = useState([]);
  const [isLogin, setIsLogin] = useState([]);
  const [token, setToken] = useState([]);
  const [onlineToken, setOnlineToken] = useState();
  //获取用户信息
  const getUserInfo = async () => {
    const res = await invokeAsyncAPi("xz_get_UserInfo");
    if (res) {
      localStorage.setItem(AUTH_USER, JSON.stringify(res));
      localStorage.setItem(AUTH_ONLINE_TOKEN, res?.user_token);
      getOldUserInfo();
    }
    setOnlineToken(res?.user_token);
    setUserInfo(res);
    console.log("获取用户信息", res);
  };

  const getOldUserInfo = async () => {
    const data = {
      username: "admin_123" || JSON.parse(localStorage.getItem(AUTH_USER))?.user_id,
      password: "1234@abc",
    };
    const { valid, token } = await System.requestToken(data);
    console.log("validvalidvalidvalid", valid, token);
    localStorage.setItem(AUTH_TOKEN, token);
    setToken(token);
    // debugger
    // if (!valid || !token) {
    //   //如果没有获取到token，就注册
    //   const { success, user, token } = await System.registerUser(data);
    //   if (success) {
    //     getOldUserInfo();
    //   } else {
    //     showToast("error", "获取token失败");
    //   }
    //   console.log("resresresresres", success, user, token);
    // } else {
    //   console.log("token", token);
    //   localStorage.setItem(AUTH_TOKEN, token);
    //   setToken(token);
    // }
  };

  //获取登录状态
  useEffect(() => {
    invokeAsyncAPi("xz_GetLoginStatus").then((res) => {
      localStorage.setItem(AUTH_LOGIN, res);
      setIsLogin(res);
      if (res) {
        getUserInfo();
      } else {
        localStorage.removeItem(AUTH_USER);
        localStorage.removeItem(AUTH_ONLINE_TOKEN);
        localStorage.removeItem(AUTH_LOGIN);
      }
      console.log("获取登录", res);
    });
  }, []);

  //监听登录状态变化
  useEffect(() => {
    registerInformApi("inform_LoginStatus", async (res) => {
      console.log("监听登录状态", res);
      localStorage.setItem(AUTH_LOGIN, res);
      setIsLogin(res);
      if (res) {
        getUserInfo();
      } else {
        localStorage.removeItem(AUTH_USER);
        localStorage.removeItem(AUTH_LOGIN);
        localStorage.removeItem(AUTH_ONLINE_TOKEN);
      }
    });
  }, []);

  //监听更新token
  useEffect(() => {
    registerInformApi("inform_UpdateUserToken", async (res) => {
      console.log("监听更新token", res);
      localStorage.setItem(AUTH_ONLINE_TOKEN, res);
      setOnlineToken(res);
    });
  }, []);
  return { userInfo, isLogin, token, onlineToken };
}
export default useUserInfo;
